#include "../include/ProjectClient.hpp"
#include <nlohmann/json.hpp>
#include <stdexcept>
#include <fmt/format.h>

ProjectClient::ProjectClient(const std::string & url)
  : cli(url)
{
  auto res=cli.Get("/hello");
  if(res==nullptr || res->status!=200)
    throw std::runtime_error("无法连接远程服务器");
}

ProjectClient::~ProjectClient()
{}

std::vector<std::string> ProjectClient::ProjectList()
{
  auto res=cli.Get("/Project/List");
  if(res==nullptr || res->status!=200)
    throw std::runtime_error("请求失败");
  nlohmann::json ret=nlohmann::json::parse(res->body);
  if(!ret.is_array())
    throw std::runtime_error("数据格式错误");
  std::vector<std::string> ret_arr;
  for(auto & e : ret)
    ret_arr.push_back(e);
  return std::move(ret_arr);
}

std::vector<std::string> ProjectClient::TaskList(const std::string & projectName)
{
  auto res=cli.Get(fmt::format("/Project/Task/List?ProjectName={}",projectName));
  if(res==nullptr || res->status!=200)
    throw std::runtime_error("请求失败");
  nlohmann::json ret=nlohmann::json::parse(res->body);
  if(!ret.is_array())
    throw std::runtime_error("数据格式错误");
  std::vector<std::string> ret_arr;
  for(auto & e : ret)
    ret_arr.push_back(e);
  return std::move(ret_arr);
}

bool ProjectClient::CreateProject(const std::string & projectname,const std::string& describe)
{
  auto res=cli.Get(fmt::format("/Project/Create?ProjectName={}&Describe={}",projectname,describe));
  if(res->status==200)
    return true;
  else 
    return false;
}

bool ProjectClient::CreateTask(const std::string & projectname,const std::string & taskname)
{
  auto res=cli.Get(fmt::format("/Project/Task/Create?ProjectName={}&TaskName={}",projectname,taskname));
  if(res->status==200)
    return true;
  else 
    return false;
}

std::vector<std::string> ProjectClient::CameraList()
{
  auto res=cli.Get(fmt::format("/Camera/List"));
  if(res==nullptr || res->status!=200)
    throw std::runtime_error("请求失败");
  nlohmann::json ret=nlohmann::json::parse(res->body);
  if(!ret.is_array())
    throw std::runtime_error("数据格式错误");
  std::vector<std::string> ret_arr;
  for(auto & e : ret)
    ret_arr.push_back(e);
  return std::move(ret_arr);
}
